﻿Imports Microsoft.Win32
Imports System
Imports System.CodeDom
Imports System.Collections
Imports System.Collections.Generic
Imports System.ComponentModel
Imports System.ComponentModel.Design
Imports System.IO
Imports System.Reflection
Imports System.Runtime.InteropServices
Imports System.Text
Imports System.Windows.Forms
Imports System.Workflow.ComponentModel
Imports System.Workflow.ComponentModel.Compiler
Imports System.Workflow.ComponentModel.Serialization
Imports System.Xml

Namespace System.Workflow.ComponentModel.Design
    Friend Class Helpers
        ' Methods
        Friend Shared Sub AddTypeProviderAssembliesFromRegistry(ByVal typeProvider As TypeProvider, ByVal serviceProvider As IServiceProvider)
            If (typeProvider Is Nothing) Then
                Throw New ArgumentNullException("typeProvider")
            End If
            If (serviceProvider Is Nothing) Then
                Throw New ArgumentNullException("serviceProvider")
            End If
            Dim key As RegistryKey = Registry.CurrentUser.OpenSubKey(Helpers.TypeProviderRegistryKeyPath)
            If (Not key Is Nothing) Then
                Dim service As ITypeProviderCreator = [TryCast](serviceProvider.GetService(GetType(ITypeProviderCreator)),ITypeProviderCreator)
                Dim str As String
                For Each str In DirectCast(key.GetValue(Helpers.TypeProviderAssemblyRegValueName), String())
                    Try 
                        If (Not service Is Nothing) Then
                            Dim flag As Boolean = True
                            Dim transientAssembly As Assembly = service.GetTransientAssembly(AssemblyName.GetAssemblyName(str))
                            If (Not transientAssembly Is Nothing) Then
                                Dim types As Type() = transientAssembly.GetTypes
                                Dim index As Integer = 0
                                Do While (index < types.Length)
                                    Dim type As Type = types(index)
                                    If (Not typeProvider.GetType(type.AssemblyQualifiedName) Is Nothing) Then
                                        flag = False
                                    End If
                                    Exit Do
                                Loop
                                If flag Then
                                    typeProvider.AddAssembly(transientAssembly)
                                End If
                            End If
                        Else
                            typeProvider.AddAssemblyReference(str)
                        End If
                    Catch obj1 As Object
                    End Try
                Next
                key.Close
            End If
        End Sub

        Friend Shared Function AreAllActivities(ByVal c As ICollection) As Boolean
            If (c Is Nothing) Then
                Throw New ArgumentNullException("c")
            End If
            Dim obj2 As Object
            For Each obj2 In c
                If Not TypeOf obj2 Is Activity Then
                    Return False
                End If
            Next
            Return True
        End Function

        Friend Shared Function CreateXmlWriter(ByVal output As Object) As XmlWriter
            Dim settings As New XmlWriterSettings { _
                .Indent = True, _
                .IndentChars = ChrW(9), _
                .OmitXmlDeclaration = True, _
                .CloseOutput = True _
            }
            If TypeOf output Is String Then
                Return XmlWriter.Create([TryCast](output,String), settings)
            End If
            If TypeOf output Is TextWriter Then
                Return XmlWriter.Create([TryCast](output,TextWriter), settings)
            End If
            Return Nothing
        End Function

        Friend Shared Sub DeserializeDesignersFromStream(ByVal activities As ICollection, ByVal stateStream As Stream)
            If (stateStream.Length <> 0) Then
                Dim reader As New BinaryReader(stateStream)
                stateStream.Seek(0, SeekOrigin.Begin)
                Dim queue As New Queue([Of] IComponent)
                Dim component As IComponent
                For Each component In activities
                    queue.Enqueue(component)
                Next
                Do While (queue.Count > 0)
                    Dim component2 As IComponent = queue.Dequeue
                    If ((Not component2 Is Nothing) AndAlso (Not component2.Site Is Nothing)) Then
                        Dim service As IDesignerHost = [TryCast](component2.Site.GetService(GetType(IDesignerHost)),IDesignerHost)
                        If (service Is Nothing) Then
                            Throw New InvalidOperationException(SR.GetString("General_MissingService", New Object() { GetType(IDesignerHost).Name }))
                        End If
                        Dim designer As ActivityDesigner = [TryCast](service.GetDesigner(component2),ActivityDesigner)
                        If (Not designer Is Nothing) Then
                            Try 
                                DirectCast(designer, IPersistUIState).LoadViewState(reader)
                                Dim activity As CompositeActivity = [TryCast](component2,CompositeActivity)
                                If (Not activity Is Nothing) Then
                                    Dim component3 As IComponent
                                    For Each component3 In activity.Activities
                                        queue.Enqueue(component3)
                                    Next
                                End If
                            Catch obj1 As Object
                            End Try
                        End If
                    End If
                Loop
            End If
        End Sub

        Friend Shared Function GetAccessType(ByVal [property] As PropertyInfo, ByVal owner As Object, ByVal serviceProvider As IServiceProvider) As AccessTypes
            If (owner Is Nothing) Then
                Throw New ArgumentNullException("owner")
            End If
            If (serviceProvider Is Nothing) Then
                Throw New ArgumentNullException("serviceProvider")
            End If
            If (Not [property] Is Nothing) Then
                Dim provider As IDynamicPropertyTypeProvider = [TryCast](owner,IDynamicPropertyTypeProvider)
                If (Not provider Is Nothing) Then
                    Return provider.GetAccessType(serviceProvider, [property].Name)
                End If
            End If
            Return AccessTypes.Read
        End Function

        Private Shared Function GetActivity(ByVal containerActivity As Activity, ByVal id As String) As Activity
            If (Not containerActivity Is Nothing) Then
                Dim queue As New Queue
                queue.Enqueue(containerActivity)
                Do While (queue.Count > 0)
                    Dim activity As Activity = DirectCast(queue.Dequeue, Activity)
                    If activity.Enabled Then
                        If (activity.Name = id) Then
                            Return activity
                        End If
                        If TypeOf activity Is CompositeActivity Then
                            Dim activity2 As Activity
                            For Each activity2 In DirectCast(activity, CompositeActivity).Activities
                                queue.Enqueue(activity2)
                            Next
                        End If
                    End If
                Loop
            End If
            Return Nothing
        End Function

        Public Shared Function GetAllEnabledActivities(ByVal compositeActivity As CompositeActivity) As IList([Of] Activity)
            If (compositeActivity Is Nothing) Then
                Throw New ArgumentNullException("compositeActivity")
            End If
            Dim list As New List([Of] Activity)(compositeActivity.EnabledActivities)
            Dim activity As Activity
            For Each activity In compositeActivity.Activities
                If (activity.Enabled AndAlso Helpers.IsFrameworkActivity(activity)) Then
                    list.Add(activity)
                End If
            Next
            Return list
        End Function

        Friend Shared Function GetAllNestedActivities(ByVal compositeActivity As CompositeActivity) As Activity()
            If (compositeActivity Is Nothing) Then
                Throw New ArgumentNullException("compositeActivity")
            End If
            Dim list As New ArrayList
            Dim queue As New Queue
            queue.Enqueue(compositeActivity)
            Do While (queue.Count > 0)
                Dim activity As CompositeActivity = DirectCast(queue.Dequeue, CompositeActivity)
                If ((activity Is compositeActivity) OrElse Not Helpers.IsCustomActivity(activity)) Then
                    Dim activity2 As Activity
                    For Each activity2 In activity.Activities
                        list.Add(activity2)
                        If TypeOf activity2 Is CompositeActivity Then
                            queue.Enqueue(activity2)
                        End If
                    Next
                    Dim activity3 As Activity
                    For Each activity3 In activity.EnabledActivities
                        If Not list.Contains(activity3) Then
                            list.Add(activity3)
                            If TypeOf activity3 Is CompositeActivity Then
                                queue.Enqueue(activity3)
                            End If
                        End If
                    Next
                End If
            Loop
            Return DirectCast(list.ToArray(GetType(Activity)), Activity())
        End Function

        Friend Shared Function GetAttributeFromObject([Of] T As Attribute)(ByVal attributeObject As Object) As T
            If TypeOf attributeObject Is AttributeInfoAttribute Then
                Return DirectCast(DirectCast(attributeObject, AttributeInfoAttribute).AttributeInfo.CreateAttribute, T)
            End If
            If TypeOf attributeObject Is T Then
                Return DirectCast(attributeObject, T)
            End If
            Return CType(Nothing, T)
        End Function

        Friend Shared Function GetBaseIdentifier(ByVal activity As Activity) As String
            Dim name As String = activity.GetType.Name
            Dim builder As New StringBuilder(name.Length)
            Dim i As Integer
            For i = 0 To name.Length - 1
                If (Char.IsUpper(name.Chars(i)) AndAlso (((i = 0) OrElse (i = (name.Length - 1))) OrElse Char.IsUpper(name.Chars((i + 1))))) Then
                    builder.Append(Char.ToLowerInvariant(name.Chars(i)))
                Else
                    builder.Append(name.Substring(i))
                    Exit For
                End If
            Next i
            Return builder.ToString
        End Function

        Friend Shared Function GetBaseType(ByVal [property] As PropertyInfo, ByVal owner As Object, ByVal serviceProvider As IServiceProvider) As Type
            If (owner Is Nothing) Then
                Throw New ArgumentNullException("owner")
            End If
            If (serviceProvider Is Nothing) Then
                Throw New ArgumentNullException("serviceProvider")
            End If
            If ([property] Is Nothing) Then
                Return Nothing
            End If
            Dim provider As IDynamicPropertyTypeProvider = [TryCast](owner,IDynamicPropertyTypeProvider)
            If (Not provider Is Nothing) Then
                Dim propertyType As Type = provider.GetPropertyType(serviceProvider, [property].Name)
                If (Not propertyType Is Nothing) Then
                    Return propertyType
                End If
            End If
            Return [property].PropertyType
        End Function

        Friend Shared Function GetClassName(ByVal fullQualifiedName As String) As String
            If (fullQualifiedName Is Nothing) Then
                Return Nothing
            End If
            Dim str As String = fullQualifiedName
            Dim num As Integer = fullQualifiedName.LastIndexOf("."c)
            If (num <> -1) Then
                str = fullQualifiedName.Substring((num + 1))
            End If
            Return str
        End Function

        Friend Shared Function GetCodeNamespaceAndClass(ByVal namespaces As CodeNamespaceCollection, ByVal namespaceName As String, ByVal className As String, <Out> ByRef codeNamespace As CodeNamespace) As CodeTypeDeclaration
            codeNamespace = Nothing
            Dim namespace2 As CodeNamespace
            For Each namespace2 In namespaces
                If (namespace2.Name = namespaceName) Then
                    codeNamespace = namespace2
                    Exit For
                End If
            Next
            If (Not codeNamespace Is Nothing) Then
                Dim declaration2 As CodeTypeDeclaration
                For Each declaration2 In codeNamespace.Types
                    If (declaration2.Name = className) Then
                        Return declaration2
                    End If
                Next
            End If
            Return Nothing
        End Function

        Friend Shared Function GetDataSourceActivity(ByVal activity As Activity, ByVal inputName As String, <Out> ByRef name As String) As Activity
            If (activity Is Nothing) Then
                Throw New ArgumentNullException("activity")
            End If
            If String.IsNullOrEmpty(inputName) Then
                Throw New ArgumentException("inputName")
            End If
            name = inputName
            If (inputName.IndexOf("."c) = -1) Then
                Return activity
            End If
            Dim length As Integer = inputName.LastIndexOf("."c)
            Dim activityName As String = inputName.Substring(0, length)
            name = inputName.Substring((length + 1))
            Dim activity2 As Activity = Helpers.ParseActivityForBind(activity, activityName)
            If (activity2 Is Nothing) Then
                activity2 = Helpers.ParseActivity(Helpers.GetRootActivity(activity), activityName)
            End If
            Return activity2
        End Function

        Friend Shared Function GetDataSourceClass(ByVal activity As Activity, ByVal serviceProvider As IServiceProvider) As Type
            If (activity Is Nothing) Then
                Throw New ArgumentNullException("activity")
            End If
            If (serviceProvider Is Nothing) Then
                Throw New ArgumentNullException("serviceProvider")
            End If
            Dim str As String = Nothing
            If (activity Is Helpers.GetRootActivity(activity)) Then
                str = [TryCast](activity.GetValue(WorkflowMarkupSerializer.XClassProperty),String)
            End If
            If String.IsNullOrEmpty(str) Then
                Return activity.GetType
            End If
            Dim service As ITypeProvider = DirectCast(serviceProvider.GetService(GetType(ITypeProvider)), ITypeProvider)
            If (service Is Nothing) Then
                Throw New InvalidOperationException(SR.GetString("General_MissingService", New Object() { GetType(ITypeProvider).Name }))
            End If
            Return service.GetType(str)
        End Function

        Friend Shared Function GetDeclaringActivity(ByVal activity As Activity) As CompositeActivity
            If (activity Is Nothing) Then
                Throw New ArgumentNullException("activity")
            End If
            Dim activity2 As CompositeActivity = activity.Parent
            Do While (Not activity2 Is Nothing)
                If (activity2.Parent Is Nothing) Then
                    Return activity2
                End If
                If Helpers.IsCustomActivity(activity2) Then
                    Return activity2
                End If
                activity2 = activity2.Parent
            Loop
            Return Nothing
        End Function

        Friend Shared Function GetDelegateFromEvent(ByVal eventInfo As EventInfo) As Type
            If (Not eventInfo.EventHandlerType Is Nothing) Then
                Return eventInfo.EventHandlerType
            End If
            Return TypeProvider.GetEventHandlerType(eventInfo)
        End Function

        Friend Shared Function GetDesignTimeTypeName(ByVal owner As Object, ByVal key As Object) As String
            Dim str As String = Nothing
            Dim obj2 As DependencyObject = [TryCast](owner,DependencyObject)
            If (((Not obj2 Is Nothing) AndAlso (Not key Is Nothing)) AndAlso obj2.UserData.Contains(UserDataKeys.DesignTimeTypeNames)) Then
                Dim hashtable As Hashtable = [TryCast](obj2.UserData.Item(UserDataKeys.DesignTimeTypeNames),Hashtable)
                If ((Not hashtable Is Nothing) AndAlso hashtable.ContainsKey(key)) Then
                    str = [TryCast](hashtable.Item(key),String)
                End If
            End If
            Return str
        End Function

        Friend Shared Function GetEnclosingActivity(ByVal activity As Activity) As Activity
            If Helpers.IsActivityLocked(activity) Then
                Return Helpers.GetDeclaringActivity(activity)
            End If
            Return Helpers.GetRootActivity(activity)
        End Function

        Friend Shared Function GetIdentifiersInCompositeActivity(ByVal compositeActivity As CompositeActivity) As IList
            Dim list As New ArrayList
            If (Not compositeActivity Is Nothing) Then
                list.Add(compositeActivity.Name)
                Dim activity As Activity
                For Each activity In Helpers.GetAllNestedActivities(compositeActivity)
                    list.Add(activity.Name)
                Next
            End If
            Return ArrayList.ReadOnly(list)
        End Function

        Private Shared Function GetInstallDirectory(ByVal getSDKDir As Boolean) As String
            Dim directoryName As String = String.Empty
            Try 
                Dim capacity As Integer = &H105
                Dim lpValueBuf As New StringBuilder(capacity)
                Dim num2 As Integer = Helpers.MsiGetProductInfoW(If(getSDKDir, "{C8A7718A-FF6D-4DDC-AE36-BBF968D6799B}", "{B644FB52-BB3D-4C43-80EC-57644210536A}"), "InstallLocation", lpValueBuf, (capacity))
                Marshal.GetLastWin32Error
                If (num2 = 0) Then
                    directoryName = lpValueBuf.ToString
                End If
            Catch obj1 As Object
            End Try
            If String.IsNullOrEmpty(directoryName) Then
                Try 
                    If Not getSDKDir Then
                        [Using] key As RegistryKey = Registry.LocalMachine.OpenSubKey(Helpers.ProductRootRegKey)
                            If (Not key Is Nothing) Then
                                directoryName = CStr(key.GetValue("InstallDir"))
                            End If
                        End [Using]
                    End If
                Catch obj2 As Object
                End Try
            End If
            If String.IsNullOrEmpty(directoryName) Then
                directoryName = Path.GetDirectoryName(Assembly.GetExecutingAssembly.Location)
            End If
            Return directoryName
        End Function

        Friend Shared Function GetInterfaceMethod(ByVal interfaceType As Type, ByVal methodName As String) As MethodInfo
            Dim info As MethodInfo = Nothing
            Dim str As String = String.Empty
            Dim name As String = String.Empty
            If (methodName.LastIndexOf("."c) > 0) Then
                str = methodName.Substring(0, methodName.LastIndexOf("."c))
                name = methodName.Substring((methodName.LastIndexOf("."c) + 1))
            End If
            If Not String.IsNullOrEmpty(str) Then
                Dim type As Type
                For Each type In interfaceType.GetInterfaces
                    If (String.Compare(type.FullName, str, StringComparison.Ordinal) = 0) Then
                        Return type.GetMethod(name)
                    End If
                Next
                Return info
            End If
            Return interfaceType.GetMethod(methodName)
        End Function

        Friend Shared Function GetMethodExactMatch(ByVal type As Type, ByVal name As String, ByVal bindingAttr As BindingFlags, ByVal binder As Binder, ByVal types As Type(), ByVal modifiers As ParameterModifier()) As MethodInfo
            Dim info2 As MethodInfo
            For Each info2 In type.GetMethods(bindingAttr)
                If If(((bindingAttr And BindingFlags.IgnoreCase) = BindingFlags.IgnoreCase), (String.Compare(info2.Name, name, StringComparison.OrdinalIgnoreCase) = 0), (String.Compare(info2.Name, name, StringComparison.Ordinal) = 0)) Then
                    Dim flag2 As Boolean = False
                    If (Not types Is Nothing) Then
                        Dim parameters As ParameterInfo() = info2.GetParameters
                        If (parameters.GetLength(0) = types.Length) Then
                            Dim i As Integer = 0
                            Do While (Not flag2 AndAlso (i < parameters.Length))
                                flag2 = ((parameters(i).ParameterType Is Nothing) OrElse Not parameters(i).ParameterType.IsAssignableFrom(types(i)))
                                i += 1
                            Loop
                        Else
                            flag2 = True
                        End If
                    End If
                    If Not flag2 Then
                        Return info2
                    End If
                End If
            Next
            Return Nothing
        End Function

        Friend Shared Sub GetNamespaceAndClassName(ByVal fullQualifiedName As String, <Out> ByRef namespaceName As String, <Out> ByRef className As String)
            namespaceName = String.Empty
            className = String.Empty
            If (Not fullQualifiedName Is Nothing) Then
                Dim length As Integer = fullQualifiedName.LastIndexOf("."c)
                If (length <> -1) Then
                    namespaceName = fullQualifiedName.Substring(0, length)
                    className = fullQualifiedName.Substring((length + 1))
                Else
                    className = fullQualifiedName
                End If
            End If
        End Sub

        Friend Shared Function GetNestedActivities(ByVal compositeActivity As CompositeActivity) As Activity()
            If (compositeActivity Is Nothing) Then
                Throw New ArgumentNullException("compositeActivity")
            End If
            Dim list2 As New ArrayList
            Dim queue As New Queue
            queue.Enqueue(compositeActivity)
            Do While (queue.Count > 0)
                Dim activity As CompositeActivity = DirectCast(queue.Dequeue, CompositeActivity)
                Dim activity2 As Activity
                For Each activity2 In DirectCast(activity.Activities, IEnumerable([Of] Activity))
                    list2.Add(activity2)
                    If TypeOf activity2 Is CompositeActivity Then
                        queue.Enqueue(activity2)
                    End If
                Next
            Loop
            Return DirectCast(list2.ToArray(GetType(Activity)), Activity())
        End Function

        Friend Shared Function GetRootActivity(ByVal activity As Activity) As Activity
            If (activity Is Nothing) Then
                Throw New ArgumentNullException("activity")
            End If
            Do While (Not activity.Parent Is Nothing)
                activity = activity.Parent
            Loop
            Return activity
        End Function

        Friend Shared Function GetRootNamespace(ByVal serviceProvider As IServiceProvider) As String
            If (serviceProvider Is Nothing) Then
                Throw New ArgumentNullException("serviceProvider")
            End If
            Dim rootNamespace As String = String.Empty
            Dim service As IWorkflowCompilerOptionsService = DirectCast(serviceProvider.GetService(GetType(IWorkflowCompilerOptionsService)), IWorkflowCompilerOptionsService)
            If ((Not service Is Nothing) AndAlso (Not service.RootNamespace Is Nothing)) Then
                rootNamespace = service.RootNamespace
            End If
            Return rootNamespace
        End Function

        Private Shared Function GetRuntimeContextGuid(ByVal currentActivity As Activity) As Guid
            Dim parent As Activity = currentActivity
            Dim guid As Guid = DirectCast(parent.GetValue(Activity.ActivityContextGuidProperty), Guid)
            Do While ((guid = Guid.Empty) AndAlso (Not parent.Parent Is Nothing))
                parent = parent.Parent
                guid = DirectCast(parent.GetValue(Activity.ActivityContextGuidProperty), Guid)
            Loop
            Return guid
        End Function

        Friend Shared Function GetSerializationVisibility(ByVal memberInfo As MemberInfo) As DesignerSerializationVisibility
            If (memberInfo Is Nothing) Then
                Throw New ArgumentNullException("memberInfo")
            End If
            Dim visible As DesignerSerializationVisibility = DesignerSerializationVisibility.Visible
            Dim customAttributes As Object() = memberInfo.GetCustomAttributes(GetType(DesignerSerializationVisibilityAttribute), True)
            If (customAttributes.Length > 0) Then
                Return [TryCast](customAttributes(0),DesignerSerializationVisibilityAttribute).Visibility
            End If
            If Attribute.IsDefined(memberInfo, GetType(DesignerSerializationVisibilityAttribute)) Then
                visible = [TryCast](Attribute.GetCustomAttribute(memberInfo, GetType(DesignerSerializationVisibilityAttribute)),DesignerSerializationVisibilityAttribute).Visibility
            End If
            Return visible
        End Function

        Friend Shared Function GetTopLevelActivities(ByVal activities As ICollection) As Activity()
            If (activities Is Nothing) Then
                Throw New ArgumentNullException("activities")
            End If
            Dim list As New List([Of] Activity)
            Dim obj2 As Object
            For Each obj2 In activities
                Dim item As Activity = [TryCast](obj2,Activity)
                If (Not item Is Nothing) Then
                    Dim flag As Boolean = False
                    Dim activity2 As Activity = item.Parent
                    Do While ((Not activity2 Is Nothing) AndAlso Not flag)
                        Dim obj3 As Object
                        For Each obj3 In activities
                            If (obj3 Is activity2) Then
                                flag = True
                                Exit For
                            End If
                        Next
                        activity2 = activity2.Parent
                    Loop
                    If Not flag Then
                        list.Add(item)
                    End If
                End If
            Next
            Return list.ToArray
        End Function

        Friend Shared Function IsActivityLocked(ByVal activity As Activity) As Boolean
            If (activity Is Nothing) Then
                Throw New ArgumentNullException("activity")
            End If
            Dim activity2 As CompositeActivity = activity.Parent
            Do While (Not activity2 Is Nothing)
                If (activity2.Parent Is Nothing) Then
                    Return False
                End If
                If Helpers.IsCustomActivity(activity2) Then
                    Return True
                End If
                activity2 = activity2.Parent
            Loop
            Return False
        End Function

        Friend Shared Function IsAlternateFlowActivity(ByVal activity As Activity) As Boolean
            If (activity Is Nothing) Then
                Return False
            End If
            Dim flag As Boolean = False
            If Not activity.UserData.Contains(GetType(AlternateFlowActivityAttribute)) Then
                flag = (activity.GetType.GetCustomAttributes(GetType(AlternateFlowActivityAttribute), True).Length <> 0)
                activity.UserData.Item(GetType(AlternateFlowActivityAttribute)) = flag
                Return flag
            End If
            Return CBool(activity.UserData.Item(GetType(AlternateFlowActivityAttribute)))
        End Function

        Friend Shared Function IsChildActivity(ByVal parent As CompositeActivity, ByVal activity As Activity) As Boolean
            Dim activity2 As Activity
            For Each activity2 In parent.Activities
                If (activity Is activity2) Then
                    Return True
                End If
                If (TypeOf activity2 Is CompositeActivity AndAlso Helpers.IsChildActivity([TryCast](activity2,CompositeActivity), activity)) Then
                    Return True
                End If
            Next
            Return False
        End Function

        Friend Shared Function IsCustomActivity(ByVal compositeActivity As CompositeActivity) As Boolean
            If (compositeActivity Is Nothing) Then
                Throw New ArgumentNullException("compositeActivity")
            End If
            If compositeActivity.UserData.Contains(UserDataKeys.CustomActivity) Then
                Return CBool(compositeActivity.UserData.Item(UserDataKeys.CustomActivity))
            End If
            Try 
                Dim activity As CompositeActivity = [TryCast](Activator.CreateInstance(compositeActivity.GetType),CompositeActivity)
                If ((Not activity Is Nothing) AndAlso (activity.Activities.Count > 0)) Then
                    compositeActivity.UserData.Item(UserDataKeys.CustomActivityDefaultName) = activity.Name
                    compositeActivity.UserData.Item(UserDataKeys.CustomActivity) = True
                    Return True
                End If
            Catch obj1 As Object
            End Try
            compositeActivity.UserData.Item(UserDataKeys.CustomActivity) = False
            Return False
        End Function

        Private Shared Function IsDeclaringActivityMatchesContext(ByVal currentActivity As Activity, ByVal context As Activity) As Boolean
            Dim compositeActivity As CompositeActivity = [TryCast](context,CompositeActivity)
            Dim declaringActivity As CompositeActivity = Helpers.GetDeclaringActivity(currentActivity)
            If (Helpers.IsActivityLocked(context) AndAlso ((compositeActivity Is Nothing) OrElse Not Helpers.IsCustomActivity(compositeActivity))) Then
                compositeActivity = Helpers.GetDeclaringActivity(context)
            End If
            Return (compositeActivity Is declaringActivity)
        End Function

        Friend Shared Function IsFileNameValid(ByVal fileName As String) As Boolean
            Dim num As Integer = (Path.GetInvalidPathChars.GetLength(0) + 5)
            Dim array As Char() = New Char(num  - 1) {}
            Path.GetInvalidPathChars.CopyTo(array, 0)
            array((num - 5)) = ":"c
            array((num - 4)) = "?"c
            array((num - 3)) = "*"c
            array((num - 2)) = "/"c
            array((num - 1)) = "\"c
            Return ((((Not fileName Is Nothing) AndAlso (fileName.Length <> 0)) AndAlso (fileName.Length <= 260)) AndAlso (fileName.IndexOfAny(array) = -1))
        End Function

        Public Shared Function IsFrameworkActivity(ByVal activity As Activity) As Boolean
            Return ((TypeOf activity Is CancellationHandlerActivity OrElse TypeOf activity Is CompensationHandlerActivity) OrElse TypeOf activity Is FaultHandlersActivity)
        End Function

        Friend Shared Function MergeNamespaces(ByVal primaryNs As String, ByVal secondaryNs As String) As String
            Dim str As String = primaryNs
            If ((Not secondaryNs Is Nothing) AndAlso (secondaryNs.Length > 0)) Then
                If ((Not str Is Nothing) AndAlso (str.Length > 0)) Then
                    str = (str & "." & secondaryNs)
                Else
                    str = secondaryNs
                End If
            End If
            If (str Is Nothing) Then
                str = String.Empty
            End If
            Return str
        End Function

        <DllImport("msi.dll", CharSet:=CharSet.Auto, SetLastError:=True, ExactSpelling:=True)> _
        Private Shared Function MsiGetProductInfoW(ByVal szProduct As String, ByVal szProperty As String, ByVal lpValueBuf As StringBuilder, ByRef pcchValueBuf As Integer) As Integer
        End Function

        Friend Shared Function PairUpCommonParentActivities(ByVal activities As ICollection) As IDictionary
            If (activities Is Nothing) Then
                Throw New ArgumentNullException("activities")
            End If
            Dim hashtable As New Hashtable
            Dim activity As Activity
            For Each activity In activities
                If (Not activity.Parent Is Nothing) Then
                    Dim list As ArrayList = DirectCast(hashtable.Item(activity.Parent), ArrayList)
                    If (list Is Nothing) Then
                        list = New ArrayList
                        hashtable.Add(activity.Parent, list)
                    End If
                    list.Add(activity)
                End If
            Next
            Return hashtable
        End Function

        Friend Shared Function ParseActivity(ByVal parsingContext As Activity, ByVal activityName As String) As Activity
            If (parsingContext Is Nothing) Then
                Throw New ArgumentNullException("parsingContext")
            End If
            If (activityName Is Nothing) Then
                Throw New ArgumentNullException("activityName")
            End If
            Dim id As String = activityName
            Dim str2 As String = String.Empty
            Dim index As Integer = activityName.IndexOf(".")
            If (index <> -1) Then
                id = activityName.Substring(0, index)
                str2 = activityName.Substring((index + 1))
                If (str2.Length = 0) Then
                    Return Nothing
                End If
            End If
            Dim containerActivity As Activity = Helpers.GetActivity(parsingContext, id)
            If (containerActivity Is Nothing) Then
                Return Nothing
            End If
            If (str2.Length > 0) Then
                If (Not TypeOf containerActivity Is CompositeActivity OrElse Not Helpers.IsCustomActivity([TryCast](containerActivity,CompositeActivity))) Then
                    Return Nothing
                End If
                Dim strArray As String() = str2.Split(New Char() { "."c })
                Dim i As Integer
                For i = 0 To strArray.Length - 1
                    Dim activity As Activity = Helpers.GetActivity(containerActivity, strArray(i))
                    If ((activity Is Nothing) OrElse Not Helpers.IsActivityLocked(activity)) Then
                        Return Nothing
                    End If
                    Dim declaringActivity As CompositeActivity = Helpers.GetDeclaringActivity(activity)
                    If (Not containerActivity Is declaringActivity) Then
                        Return Nothing
                    End If
                    containerActivity = activity
                Next i
                Return containerActivity
            End If
            If (Helpers.IsActivityLocked(containerActivity) AndAlso Not Helpers.IsDeclaringActivityMatchesContext(containerActivity, parsingContext)) Then
                Return Nothing
            End If
            Return containerActivity
        End Function

        Friend Shared Function ParseActivityForBind(ByVal context As Activity, ByVal activityName As String) As Activity
            If (context Is Nothing) Then
                Throw New ArgumentNullException("context")
            End If
            If (activityName Is Nothing) Then
                Throw New ArgumentNullException("activityName")
            End If
            If String.Equals(activityName, "/Self", StringComparison.Ordinal) Then
                Return context
            End If
            If activityName.StartsWith("/Parent", StringComparison.OrdinalIgnoreCase) Then
                Dim activity As Activity = context
                Dim strArray As String() = activityName.Split(New Char() { "/"c }, StringSplitOptions.RemoveEmptyEntries)
                Dim i As Integer = 0
                Do While ((i < strArray.Length) AndAlso (Not activity Is Nothing))
                    activity = If(String.Equals(strArray(i).Trim, "Parent", StringComparison.OrdinalIgnoreCase), activity.Parent, Nothing)
                    i += 1
                Loop
                Return activity
            End If
            If Not Helpers.IsActivityLocked(context) Then
                Dim activityByName As Activity = Nothing
                Dim activity8 As Activity = context
                Dim flag As Boolean = False
                Dim compositeActivity As CompositeActivity = [TryCast](activity8,CompositeActivity)
                If (((Not compositeActivity Is Nothing) AndAlso (Not activity8.Parent Is Nothing)) AndAlso Helpers.IsCustomActivity(compositeActivity)) Then
                    flag = True
                    activity8 = activity8.Parent
                End If
                Do While ((activityByName Is Nothing) AndAlso (Not activity8 Is Nothing))
                    activityByName = activity8.GetActivityByName(activityName, True)
                    activity8 = activity8.Parent
                Loop
                If (flag AndAlso (activityByName Is Nothing)) Then
                    activityByName = context.GetActivityByName(activityName, True)
                End If
                If (Not activityByName Is Nothing) Then
                    Return activityByName
                End If
                Return Helpers.ParseActivity(Helpers.GetRootActivity(context), activityName)
            End If
            Dim activity2 As Activity = Nothing
            Dim declaringActivity As Activity = Helpers.GetDeclaringActivity(context)
            Dim runtimeContextGuid As Guid = Helpers.GetRuntimeContextGuid(context)
            Dim guid2 As Guid = Helpers.GetRuntimeContextGuid(declaringActivity)
            Dim parsingContext As Activity = context
            Dim parent As Activity = context.Parent
            Dim guid3 As Guid = Helpers.GetRuntimeContextGuid(parent)
            Do While ((activity2 Is Nothing) AndAlso (guid2 <> runtimeContextGuid))
                Do While ((Not parent Is Nothing) AndAlso (guid3 = runtimeContextGuid))
                    parsingContext = parent
                    parent = parent.Parent
                    guid3 = Helpers.GetRuntimeContextGuid(parent)
                Loop
                activity2 = Helpers.ParseActivity(parsingContext, activityName)
                runtimeContextGuid = guid3
            Loop
            If (activity2 Is Nothing) Then
                activity2 = Helpers.ParseActivity(declaringActivity, activityName)
            End If
            If (activity2 Is Nothing) Then
                If Not declaringActivity.UserData.Contains(UserDataKeys.CustomActivityDefaultName) Then
                    Dim activity6 As Activity = [TryCast](Activator.CreateInstance(declaringActivity.GetType),Activity)
                    declaringActivity.UserData.Item(UserDataKeys.CustomActivityDefaultName) = activity6.Name
                End If
                If (CStr(declaringActivity.UserData.Item(UserDataKeys.CustomActivityDefaultName)) = activityName) Then
                    activity2 = declaringActivity
                End If
            End If
            Return activity2
        End Function

        Friend Shared Function SerializeDesignersToStream(ByVal activities As ICollection) As Stream
            Dim output As Stream = New MemoryStream
            Dim writer As New BinaryWriter(output)
            Dim queue As New Queue([Of] IComponent)
            Dim component As IComponent
            For Each component In activities
                queue.Enqueue(component)
            Next
            Do While (queue.Count > 0)
                Dim component2 As IComponent = queue.Dequeue
                If ((Not component2 Is Nothing) AndAlso (Not component2.Site Is Nothing)) Then
                    Dim service As IDesignerHost = [TryCast](component2.Site.GetService(GetType(IDesignerHost)),IDesignerHost)
                    If (service Is Nothing) Then
                        Throw New InvalidOperationException(SR.GetString("General_MissingService", New Object() { GetType(IDesignerHost).Name }))
                    End If
                    Dim designer As ActivityDesigner = [TryCast](service.GetDesigner(component2),ActivityDesigner)
                    If (Not designer Is Nothing) Then
                        Try 
                            DirectCast(designer, IPersistUIState).SaveViewState(writer)
                            Dim activity As CompositeActivity = [TryCast](component2,CompositeActivity)
                            If (Not activity Is Nothing) Then
                                Dim component3 As IComponent
                                For Each component3 In activity.Activities
                                    queue.Enqueue(component3)
                                Next
                            End If
                        Catch obj1 As Object
                        End Try
                    End If
                End If
            Loop
            Return output
        End Function

        Friend Shared Sub SetDesignTimeTypeName(ByVal owner As Object, ByVal key As Object, ByVal value As String)
            Dim obj2 As DependencyObject = [TryCast](owner,DependencyObject)
            If ((Not obj2 Is Nothing) AndAlso (Not key Is Nothing)) Then
                If Not obj2.UserData.Contains(UserDataKeys.DesignTimeTypeNames) Then
                    obj2.UserData.Item(UserDataKeys.DesignTimeTypeNames) = New Hashtable
                End If
                Dim hashtable As Hashtable = [TryCast](obj2.UserData.Item(UserDataKeys.DesignTimeTypeNames),Hashtable)
                hashtable.Item(key) = value
            End If
        End Sub

        Friend Shared Function TypesEqual(ByVal typeLeft As CodeTypeReference, ByVal typeRight As CodeTypeReference) As Boolean
            If (typeLeft.ArrayRank <> typeRight.ArrayRank) Then
                Return False
            End If
            If Not typeLeft.BaseType.Equals(typeRight.BaseType) Then
                Return False
            End If
            If (typeLeft.ArrayRank > 0) Then
                Return Helpers.TypesEqual(typeLeft.ArrayElementType, typeRight.ArrayElementType)
            End If
            Return True
        End Function

        Friend Shared Function TypesEqual(ByVal typeLeft As CodeTypeReference, ByVal typeRight As Type) As Boolean
            If (typeRight.IsArray AndAlso (typeLeft.ArrayRank <> typeRight.GetArrayRank)) Then
                Return False
            End If
            If Not typeLeft.BaseType.Equals(typeRight.FullName) Then
                Return False
            End If
            If (typeLeft.ArrayRank > 0) Then
                Return Helpers.TypesEqual(typeLeft.ArrayElementType, typeRight.GetElementType)
            End If
            Return True
        End Function

        Friend Shared Sub UpdateTypeProviderAssembliesRegistry(ByVal assemblyName As String)
            Dim key As RegistryKey = Registry.CurrentUser.CreateSubKey(Helpers.TypeProviderRegistryKeyPath)
            If (Not key Is Nothing) Then
                Try 
                    Dim list As ArrayList = Nothing
                    If (key.ValueCount > 0) Then
                        list = New ArrayList(DirectCast(key.GetValue(Helpers.TypeProviderAssemblyRegValueName), String()))
                    Else
                        list = New ArrayList
                    End If
                    If Not list.Contains(assemblyName) Then
                        list.Add(assemblyName)
                        key.SetValue(Helpers.TypeProviderAssemblyRegValueName, DirectCast(list.ToArray(GetType(String)), String()))
                    End If
                Catch obj1 As Object
                Finally
                    key.Close
                End Try
            End If
        End Sub


        ' Properties
        Friend Shared ReadOnly Property PerUserRegistryKey As String
            Get
                Dim str As String = String.Empty
                [Using] key As RegistryKey = Application.UserAppDataRegistry
                    str = key.ToString.Substring((Registry.CurrentUser.ToString.Length + 1))
                    str = str.Substring(0, str.LastIndexOf("\"))
                    Return (str & "\" & Helpers.VSExtensionProductRegistrySubKey)
                End [Using]
            End Get
        End Property

        Private Shared ReadOnly Property TypeProviderRegistryKeyPath As String
            Get
                Return (Helpers.PerUserRegistryKey & "\TypeProvider")
            End Get
        End Property


        ' Fields
        Friend Const FILENAME_MAX As Integer = 260
        Private Const INSTALLPROPERTY_INSTALLLOCATION As String = "InstallLocation"
        Private Const ProductCode As String = "{B644FB52-BB3D-4C43-80EC-57644210536A}"
        Friend Shared ReadOnly ProductInstallDirectory As String = Helpers.GetInstallDirectory(False)
        Friend Shared ReadOnly ProductRootRegKey As String = "SOFTWARE\Microsoft\Net Framework Setup\NDP\v3.0\Setup\Windows Workflow Foundation"
        Private Const ProductSDKCode As String = "{C8A7718A-FF6D-4DDC-AE36-BBF968D6799B}"
        Friend Shared ReadOnly ProductSDKInstallDirectory As String = Helpers.GetInstallDirectory(True)
        Friend Shared ReadOnly TypeProviderAssemblyRegValueName As String = "References"
        Private Shared ReadOnly VSExtensionProductRegistrySubKey As String = "Visual Studio Ext for Windows Workflow"
    End Class
End Namespace

